from jinja2 import Environment, PackageLoader
import re, json
from spreadsheetdb import *
from uoitproc import aggregate, restrict_by_date
from datetime import datetime, timedelta
from pprint import pprint

BASE = ""
env = Environment(loader=PackageLoader('spreadsheetdb', 'templates'))

def authors(s):
  if not s:
    return "-"
  author_list = re.split(r'\s+and\s+', s.replace(",", " and "))
  if len(author_list) > 1:
    return "%s and %s" % (", ".join(author_list[:-1]), author_list[-1])
  else:
    return author_list[0]

def email(x):
  return x.replace(".", " DOT ").replace("@", " AT ")

def month(x):
  if not x:
    return ""
  m = ['Jan', 'Feb', 'Mar', 'Apr',
       'May', 'Jun', 'Jul', 'Aug',
       'Sep', 'Oct', 'Nov', 'Dec']

  if type(x) == int or re.match(r'\d+', x):
    return m[int(x)-1]
  y = [_ for _ in m if x.lower().startswith(_.lower())]
  if y:
    return y[0]
  if x.lower().startswith("winter"):
    return 'Jan'
  if x.lower().startswith("fall"):
    return 'Sep'

  return x

def modifiedtime(x):
  d = datetime.strptime(x[:-5],"%Y-%m-%dT%H:%M:%S") - timedelta(hours=4)
  return d.strftime("%a %b %d %Y, %I:%M:%S %p")

def degree(x):
  x = x.upper()
  if x == 'PHD':
    x = 'PhD'
  elif x == 'MSC':
    x = 'MSc'
  elif x == 'MASC':
    x = 'MASc'
  return x

def money(x):
  if not x:
    return "N/A"
  try:
    return "$%d" % int(x)
  except:
    return x

env.filters['authors'] = authors
env.filters['isnull'] = lambda x: ("" if x == None else x)
env.filters['email'] = email
env.filters['month'] = month
env.filters['modifiedtime'] = modifiedtime
env.filters['degree'] = degree
env.filters['money'] = money

def make_public_page(p):
  aggr = aggregate(p, context="public")
  p.update(x_pub_year=aggr.x_pub_year, # publication & talks
           x_pub_type=aggr.x_pub_type, 
           x_courses=aggr.x_courses,
           x_supervision=aggr.x_supervision,
           x_fundings=aggr.x_fundings,
           x_talks=aggr.x_talks)

  html = env.get_template("public.html").render(p=p, BASE=BASE)
  return html.encode('ascii', 'xmlcharrefreplace')

def make_activity_report(p, start, end):
  restrict_by_date(p, start, end)
  aggr = aggregate(p, context="private")

  p.update(x_pub_type=aggr.x_pub_type,  # publication
           x_talks=aggr.x_talks,        # events
           x_fundings=aggr.x_fundings,  # successful funding
           x_pending=aggr.x_pending,    # funding applied
           x_students=aggr.x_students,  # supervision
           x_services=aggr.x_services)  # service

  html = env.get_template("activityreport.html").render(
          BASE=BASE, p=p, 
          yearstart=start[0], monthstart=start[1],
          yearend=end[0], monthend=end[1])
  return html.encode('ascii', 'xmlcharrefreplace')
